package com.zlm.security;

import com.zlm.entity.Menu;
import com.zlm.service.MenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private MenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 自定义动态权限元数据信息
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        // 1.object表示当前的请求对象
        String requestURI = ((FilterInvocation) object).getRequest().getRequestURI();

        // 得到所有的菜单，以及当前的请求路径
        // 2.查询所有的菜单
        List<Menu> allMenu = menuService.getAllMenu();

        // 3.遍历每一个菜单
        for (Menu menu : allMenu) {
            // 3.1.如果当前路径和我们请求的路径是一样的话
            if (antPathMatcher.match(menu.getPattern(), requestURI)) {
                // 3.2.把菜单的角色都转为一个数组
                String[] roles = menu.getRoles().stream().map(r -> r.getName()).toArray(String[]::new);
                // 放入ConfigAttribute里面
                return SecurityConfig.createList(roles);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        // 这个是根据源码直接复制过来的
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
